package com.zzyl.intercept;


import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.AdminCacheConstant;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前请求是否是handler()
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取token
        String token = request.getHeader(Constants.USER_TOKEN);
        //token是否为空 如果是空，抛异常 登录状态失效，请重新登录
        if(StringUtils.isEmpty(token)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //解析token
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        log.info("拦截token内容：claims：{}"+claims);
        //token内容是否为空 如果是空，抛异常 登录状态失效，请重新登录
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //获取用户数据
        String userJson = String.valueOf(claims.get("currentUser"));
        //JSON转成UserVo对象
        UserVo userVo = JSONUtil.toBean(userJson, UserVo.class);
        //从redis获取url列表
        String key = AdminCacheConstant.PUBLIC_ACCESS_URLS+userVo.getId();

       String urlJson = redisTemplate.opsForValue().get(key);
        // 获取url列表 将json转成字符串list
        List<String> urlList =null;
        if (StringUtils.isNotEmpty(urlJson)){
            urlList = JSONUtil.toList(urlJson, String.class);
        }

        //获取当前请求路径
       String targetUrl = request.getMethod()+request.getRequestURI();
        log.info("拦截器，当前请求路径：{}"+targetUrl);

        //匹配当前路径是否存在urlList集合中
        for (String url : urlList) {
            if (antPathMatcher.match(url,targetUrl)){
                //将url列表 存储到当前线程中
                UserThreadLocal.setSubject(userJson);
                return true;
            }
        }
        log.error("拦截器，当前请求路径：{}  不在权限列表中"+targetUrl);

        //权限不足抛异常
        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除当前线程中的数据
        UserThreadLocal.removeSubject();
    }
}
